import { createSlice } from '@reduxjs/toolkit'

const carSlice = createSlice({
    name:'car',
    initialState:{
        carList:[]
    },
    reducers:{
        addCar(state, {payload}){
            console.log('payload: ', payload)
            // 1. 判断id商品是否已在购物车，如果在将buyNum数据 + 1，不在新增
            let index = state.carList.findIndex(item=>item.id === payload.id)
            if(index !== -1){
                state.carList[index].buyNum += 1
            }else{
                state.carList.push({
                    ...payload,
                    buyNum:1
                })
            }
            
        }
    }
})

export default carSlice.reducer
export const {addCar} = carSlice.actions